<template>
  <view class="page">
    <uni-card style="background-color: black;">
      <template v-slot:title>
        <view class="card-title-container">
          <view class="card-title">
            巴博丝会员卡 {{ member.style }}
          </view>
        </view>
      </template>
      <view class="card-body">会员：{{ member.name }}</view>
      <view class="card-body">手机：{{ member.mobile }}</view>
      <view class="card-body">性别：{{ member.gender ? '男' : '女' }}</view>
      <view class="card-body">剩余：{{ member.count }}次</view>
      <view class="member-qrcode">
        <canvas id="qrcode" canvas-id="qrcode" style="width:80px;height:80px;"></canvas>
      </view>
    </uni-card>
    
    <view class="actions">
      <button @click="doHexiao" type="default" size="mini" style="background-color: #3c9cff;">
        <uni-icons type="scan" size="15" color="#fff"></uni-icons>
        核销
      </button>
      <button @click="doChongzhi" type="default" size="mini" style="background-color: #5bc724;">
        <uni-icons type="fire" size="15" color="#fff"></uni-icons>
        充值
      </button>
      <button @click="saveQrcode" type="default" size="mini" style="background-color: #faae3e;">
        <uni-icons type="download" size="15" color="#fff"></uni-icons>
        保存二维码
      </button>
      <button @click="showDelete" type="default" size="mini" style="background-color: #f46c6c;">
        <uni-icons type="trash" size="15" color="#fff"></uni-icons>
        删除
      </button>
    </view>
    
    <!-- 历史 -->
    <History :list="historyList" :summary="summary"></History>
    
    <!-- 充值对话框 -->
    <uni-popup ref="popupCz" type="dialog">
    	<uni-popup-dialog type="info" title="会员卡充值" @close="$refs.popupCz.close()" @confirm="saveChongzhi" :before-close="true">
        <!--  -->
        <view class="dialog-container">
          <view class="dialog-row">
            会员：{{ member.name }}
          </view>
          <view class="dialog-row">
            手机：{{ member.mobile }}
          </view>
          <view class="dialog-row" style="display: flex; align-items: center;">
            卡别：<uni-data-select
                    v-model="formData.cardId"
                    :localdata="cardList"
                    :clear="false"
                    @change="onCardChange"
                  ></uni-data-select>
          </view>
          <view class="dialog-row" style="display: flex; align-items: center;">
            充值：<uni-number-box @change="onNumberChange" v-model="formData.price" :step="step" :min="0" :max="5000"></uni-number-box>&nbsp;元
          </view>
          <view class="dialog-row">
            次数：{{ formData.count }} 次
          </view>
        </view>
        <!--  -->
      </uni-popup-dialog>
    </uni-popup>
    
    <!-- 核销对话框 -->
    <uni-popup ref="popupHx" type="dialog">
    	<uni-popup-dialog type="info" title="会员卡核销" @close="$refs.popupHx.close()" @confirm="saveHexiao" :before-close="true">
        <!--  -->
        <view class="dialog-container">
          <view class="">
            会员：{{ member.name }}
          </view>
          <view class="dialog-row">
            手机：{{ member.mobile }}
          </view>
          <view class="dialog-row" style="display: flex;">
            核销：<uni-number-box @change="onHxNumChange" v-model="formData.count"></uni-number-box>&nbsp;次
          </view>
          <view class="dialog-row">
            剩余：{{ currCountLeft }} &nbsp;次
          </view>
        </view>
        <!--  -->
      </uni-popup-dialog>
    </uni-popup>
    
    <!-- 删除确认对话框 -->
    <uni-popup ref="popupDel" type="dialog">
    	<uni-popup-dialog 
        mode="base"
        title="系统提示"
        content="该操作将删除用户账户及其相关充值、核销历史，数据一旦删除后将无法恢复，确定要删除吗？"
        :confirmText="`${ secondsLeft ? '确定(' + secondsLeft + ')'  : '确定' }`" 
        :before-close="true" 
        @close="cancleDelete" 
        @confirm="doDelete"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
  import { getMemberById, getCardList4Select, getCardById, saveHistory, getHistoryList, updateMemberCount, getSummary, deleteMemberAndHistory } from '../../utils/storage.js'
  import UQRCode from 'uqrcodejs'
  export default {
    onLoad(options) {
      const { id, type } = options
      // console.log(id, type)
      this.scanType = type
      const member = getMemberById(id)
      this.member = member
      this.cardList = getCardList4Select()
      this.historyList = getHistoryList(id)
      // console.log(this.historyList)
      this.summary = getSummary(id)
    },
    onBackPress() {
      uni.switchTab({
        url: '/pages/member/member'
      })
      return true
    },
    onReady() {
      // 获取uQRCode实例
      var qr = new UQRCode()
      // 设置二维码内容
      qr.data = this.member.id
      // 设置二维码大小，必须与canvas设置的宽高一致
      qr.size = 80
      qr.foregroundImageSrc = '/static/logo.png'
      // 调用制作二维码方法
      qr.make()
      // 获取canvas上下文
      var canvasContext = uni.createCanvasContext('qrcode', this) // 如果是组件，this必须传入
      // 设置uQRCode实例的canvas上下文
      qr.canvasContext = canvasContext
      // 调用绘制方法将二维码图案绘制到canvas上
      qr.drawCanvas()
      
      // 根据type判断出是否从扫码界面过来
      if (this.scanType != undefined) {
        if(this.scanType == 0) {
          this.$refs.popupCz.open()
        } else {
          this.$refs.popupHx.open()
        }
      }
    },
    data() {
      return {
        member: {},
        formData: { price: 0, count: 0 },
        cardList: [],
        step: 1,
        currCard: {},
        historyList: [],
        currCountLeft: 0,
        summary: {},
        secondsLeft: 5,
        secondsInterval: null,
        // popupDel: false,
        scanType: undefined
      }
    },
    methods: {
      doHexiao() {
        this.formData.count = 0
        this.currCountLeft = this.member.count
        this.$refs.popupHx.open()
      },
      doChongzhi() {
        this.formData.cardId = 0
        this.formData.price = 0
        this.$refs.popupCz.open()
      },
      onCardChange(id) {
        this.currCard = getCardById(id)
        this.formData.price = this.currCard.price
        this.formData.count = this.currCard.count
        this.step = this.currCard.price
        // console.log(id, this.currCard)
      },
      onNumberChange(num) {
        this.formData.count = (num / this.step) * this.currCard.count
        // console.log(num, this.step, this.formData.count)
      },
      onHxNumChange(num) {
        this.currCountLeft = this.member.count - num
        // console.log(num)
      },
      saveChongzhi() {
        saveHistory({ 
          id: Date.now(), 
          ...this.formData, 
          mid: this.member.id, 
          type: 0,
          countLeft: this.member.count + this.formData.count
        })
        // console.log(this.formData, this.member)
        // 
        updateMemberCount(this.member.id, this.formData.count, 0)
        this.historyList = getHistoryList(this.member.id)
        // 
        const member = getMemberById(this.member.id)
        this.member = member
        //
        this.summary = getSummary(this.member.id)
        
        uni.showToast({
          title: '充值成功！'
        })
        this.$refs.popupCz.close()
      },
      saveHexiao() {
        saveHistory({ 
          id: Date.now(), 
          count: this.formData.count, 
          countLeft: this.member.count - this.formData.count, 
          mid: this.member.id, 
          type: 1
        })
        // console.log(this.formData, this.member)
        // 
        updateMemberCount(this.member.id, this.formData.count, 1)
        this.historyList = getHistoryList(this.member.id)
        // 
        const member = getMemberById(this.member.id)
        this.member = member
        // 
        this.summary = getSummary(this.member.id)
        
        uni.showToast({
          title: '核销成功！'
        })
        this.$refs.popupHx.close()
      },
      showDelete() {
        this.secondsLeft = 5
        this.$refs.popupDel.open()
        this.secondsInterval = setInterval(() => {
          this.secondsLeft--
          if (this.secondsLeft <= 0) {
            clearInterval(this.secondsInterval)
          }
        }, 1000)
        /* uni.showModal({
          title: '系统提示',
          content: '该操作将删除用户账户及其相关充值、核销历史，数据一旦删除后将无法恢复，确定要删除吗？',
          confirmText: `确定(${this.secondsLeft})`,
          confirmColor: '#ccc'
        })
        */
      },
      cancleDelete() {
        clearInterval(this.secondsInterval)
        this.$refs.popupDel.close()
      },
      doDelete() {
        if (this.secondsLeft) {
          return
        }
        deleteMemberAndHistory(this.member.id)
        this.$refs.popupDel.close()
        uni.showToast({
          title: '用户删除成功！'
        })
        uni.switchTab({
          url: '/pages/member/member'
        })
      },
      saveQrcode() {
        uni.canvasToTempFilePath({
          canvasId: 'qrcode',
          fileType: 'png',
          width: 800,
          height: 800,
          success: res => {
            // console.log(res)
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: res => {
                uni.showToast({
                  title: '保存成功！'
                })
              },
              fail: err => {
                uni.showToast({
                  icon: 'error',
                  title: '失败，请重试！'
                })
              }
            })
          },
          fail: err => {
            // console.log(err)
            uni.showToast({
              icon: 'error',
              title: '失败，请重试！'
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  /* page {
    padding: 20rpx;
  } */
  .actions {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
  }
  uni-button {
    margin: 0;
    color: #fff;
    padding: 0 25rpx 3rpx;
  }
  .uni-icons {
    position: relative;
    top: 1px;
  }
  
  .dialog-container {
    display: flex;
    flex-direction: column;
    width: 100%;
  }
  .dialog-row {
    margin: 15rpx 0;
  }
  :deep(.uni-card__content) {
    padding: 10px 0 !important;
  }
  .member-qrcode {
    position: absolute;
    top: 55px;
    right: 10px;
    background-color: #fff;
    padding: 5px;
    box-sizing: border-box;
  }
</style>
